<template>
  <a-card :bordered="false">
    <a-row >
      <a-col :span="5">
        <a-tree
          :tree-data="treeData"
          showLine
          show-icon
          v-if="treeData.length"
          defaultExpandAll
          @select="onSelect"
          :defaultExpandedKeys="[0]">
          <a-icon slot="switcherIcon" style="font-size: 20px;" type="caret-right" />
          <template slot="custom" slot-scope="item">
            <span>{{ item.title }}</span>
            <a style="margin-left: 50%;" @click="$refs.modal.add(item)"><a-icon type="plus" /></a>
          </template>
        </a-tree>
      </a-col>
      <a-col :span="19">
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="10">
              <a-col :sm="8">
                <a-form-item label="用户名称">
                  <a-input style="width:200px;" placeholder="请输入" v-model="queryParam.userName"/>
                </a-form-item>
              </a-col>
              <a-col :sm="2">
                <span class="table-page-search-submitButtons">
                  <a-button type="primary" @click="this.fetch">查询</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <a-table
          :columns="columns"
          :dataSource="data"
          :rowKey="record => record.userId"
          :pagination="pagination"
          bordered
          @change="handleTableChange"
        >
          <span slot="enable" slot-scope="text, record">
            <template>
              <a-switch :checked="record.status=='1'" @change="enableChange(record)" />
            </template>
          </span>
          <span slot="action" slot-scope="text, record">
            <template>
              <a @click="handleEdit(record)"><a-icon type="edit" />编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确认删除?"
                @confirm="() => handleDel(record.userId)"
              >
                <a-divider type="vertical" />
                <a href="javascript:;"><a-icon type="delete" />删除</a>
              </a-popconfirm>
              <a-divider type="vertical" />
              <a @click="configRole(record)"><a-icon type="setting" />角色配置</a>
            </template>
          </span>
        </a-table>
      </a-col>
    </a-row>
    <user-modal ref="modal" @ok="handleOk" />
    <a-modal v-model="visible" :title="user.userName" :footer="null" :width="800">
      <a-transfer
        :data-source="mockData"
        show-search
        :list-style="{
          width: '320px',
          height: '400px',
        }"
        :operations="['选择', '取消']"
        :target-keys="targetKeys"
        :render="item => `${item.title}-${item.description}`"
        @change="handleChange"
      >
        <a-button
          slot="footer"
          size="small"
          style="float:right;margin: 5px"
          @click="getMock"
        >
          刷新
        </a-button>
        <span slot="notFoundContent">
          没数据
        </span>
      </a-transfer>
    </a-modal>
  </a-card>


</template>

<script>
  import {axios} from '../../utils/request'
  import UserModal  from './UserModal'
  import pick from 'lodash.pick'
  export default {
    name: 'UserList',
    components:{
      UserModal
    },
    created () {
      this.fetch()
      this.getTreeUnitData()
    },
    data () {
      return {
        treeData:[],
        visible:false,
        user:{userName:'',userId:0},
        // 表头
        columns: [
          {
            title: '所属单位',
            dataIndex: 'unitName'
          },
          {
            title: '用户名称',
            dataIndex: 'userName'
          },
          {
            title: '登录名称',
            dataIndex: 'logName'
          },
          {
            title: '密码',
            dataIndex: 'password'
          },
          {
            title: '创建时间',
            dataIndex: 'createTime'
          },
          {
            title: '状态',
            dataIndex: 'status',
            scopedSlots: { customRender: 'enable' }
          },
          {
            title: '操作',
            dataIndex: 'action',
            scopedSlots: { customRender: 'action' }
          }
        ],
        data:[],
        pagination: {
          current:1,
          total: 0,
          pageSize: 10,//每页中显示10条数据
          showSizeChanger: true,
          pageSizeOptions: ['10','20', '50', '100'],//每页中显示的数据
          showTotal: total => `共有 ${total} 条数据`,  //分页中显示总的数据
        },
        queryParam:{
          page:1,
          pageSize:10,
          userName:'',
          unitId:0
        },
        mockData: [],
        targetKeys: []
      }
    },

    methods: {
      fetch(){
        axios({
          url: '/user/listPageUser',
          method: 'get',
          params: this.queryParam
        }).then(response => {
          if(response.code==200){
            this.data = response.result
            this.pagination.total=response.total
          }else{
            this.$message.error(response.message)
          }

        })
      },
      getTreeUnitData(){
        axios.get('/unit/listUnit').then(response=>{
            if(response.code==200){
              this.buildTree(response.result,this.treeData,0)
            }else{
              this.$message.error('获取树级单位失败！')
            }
        })
      },
      buildTree (list, treeData, upUnitId) {
        list.forEach(item => {
          if (item.upUnitId === upUnitId) {
            const child = {
              key: item.unitId,
              title: item.unitName,
              scopedSlots: { title: 'custom' },
              children: []
            }
            this.buildTree(list, child.children, item.unitId)
            treeData.push(child)
          }
        })
      },
      handleTableChange(pagination, filters, sorter) {
        this.pagination.current = pagination.current
        this.pagination.pageSize = pagination.pageSize
        this.queryParam.page = pagination.current
        this.queryParam.pageSize = pagination.pageSize
        this.fetch()
      },
      onSelect(selectedKeys, info){
        this.queryParam.unitId=selectedKeys[0]
        this.fetch()
      },
      handleEdit(record){
        this.$refs.modal.edit(record)
      },
      handleDel(userId){
        axios.delete('/user/delete/'+userId).then(response=>{
          if(response.code==200){
            this.$message.success('删除成功！')
            this.fetch()
          }else{
            this.$message.error('删除失败！')
          }
        })
      },
      handleOk(){
        this.fetch()
      },
      enableChange(record){
         record.status = record.status == 0? 1 : 0
         axios.post('/user/updateStatus',pick(record, 'userId', 'status')).then(response=>{
          if(response.code==200){
            this.fetch()
            this.$message.success('更新成功！')
          }else{
            this.$message.error('更新失败！')
          }
        })
      },
      configRole(record){
          this.visible=true
          this.user.userName=record.userName+'角色配置'
          this.user.userId = record.userId
          this.getMock()
      },
      getMock() {

        axios.get('/user/getRoleList/'+this.user.userId)
          .then(response=>{
            if(response.code==200){
             const result = response.result
              const targetKeys = []
              const mockData = []

              result.forEach((item)=>{
                const data = {
                  key: item.roleId.toString(),
                  title: item.roleName,
                  description: item.describe,
                  chosen: item.chosen
                }
                if (data.chosen) {
                  targetKeys.push(data.key)
                }
                mockData.push(data)
              })
              this.mockData = mockData
              this.targetKeys = targetKeys
            }else{
              this.$message.error('角色列表获取失败')
            }
          })
      },
      handleChange(targetKeys, direction, moveKeys) {
        this.targetKeys = targetKeys
        const params = new URLSearchParams()
        params.append('userId', this.user.userId)
        params.append('roles', targetKeys.join(','))
        axios.post('/user/configRole',params)
        .then(response=>{
                if(response.code==200){
                  this.$message.success('角色配置成功！')
                  this.getMock()
                }else{
                  this.$message.error('角色配置失败！')
                }
        })
      },

    }
  }
</script>

<style lang="less">
  .ant-tree-title{
    font-size: 14px;
  }
</style>
